package com.chenfan.process.config.bean;

import com.chenfan.infra.utils.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Objects;

/**
 * @author liuming
 * @date 2022/3/21
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    private static String[] default_header_name = {"Authorization", "app_key", "tenantId"};
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(attributes)) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String header = request.getHeader(headerName);
            if(StringUtils.equalsAnyIgnoreCase(headerName, default_header_name)) {
                requestTemplate.header(headerName, header);
            }
        }
    }
}
